<template>
  <div class="app-container">
    <el-row :gutter="4">
      <el-col :xs="24">
        <el-card shadow="never">
          <template #header>
            <div class="flex flex-star">
              <div>
                <el-button
                  v-throttle="handleDownload"
                  type="primary"
                  :disabled="ids.length === 0"
                >
                  <svg-icon
                    :icon-class="'fd_filleupload'"
                    style="margin-right: 5px; font-size: 18px"
                  />{{ $t("studymaterial.BatchDownload") }}</el-button
                >
              </div>
            </div>
          </template>

          <template #default>
            <el-breadcrumb
              class="flex items-center"
              style="margin-left: 14px; margin-top: -5px; margin-bottom: 5px"
              :separator-icon="ArrowRight"
            >
              <span
                v-if="breadcrumbs.length > 1"
                v-throttle="goBack"
                style="color: var(--el-menu-active-color); cursor: pointer"
              >
                {{ $t("studymaterial.Ebene") }} |&nbsp;&nbsp;
              </span>
              <transition-group name="breadcrumb">
                <el-breadcrumb-item
                  v-for="(item, index) in breadcrumbs"
                  :key="index"
                >
                  <div
                    v-if="index === breadcrumbs.length - 1"
                    :class="
                      breadcrumbs.length - 1 !== 0
                        ? 'text-[var(--el-disabled-text-color)]'
                        : 'title'
                    "
                  >
                    {{
                      index === 0 ? $t("studymaterial.AlleDateien") : item.name
                    }}
                  </div>
                  <a
                    v-if="index !== breadcrumbs.length - 1"
                    style="font-weight: normal"
                    @click.prevent="handleLink(item)"
                  >
                    {{
                      index === 0 ? $t("studymaterial.AlleDateien") : item.name
                    }}
                  </a>
                </el-breadcrumb-item>
              </transition-group>
            </el-breadcrumb>
            <el-table
              ref="tableRef"
              v-loading="loading"
              :max-height="calculatedValue"
              :data="fileList"
              :highlight-current-row="true"
              @cell-mouse-enter="handleMouseEnter"
              @cell-mouse-leave="handleMouseLeave"
              @selection-change="handleSelectionChange"
            >
              <!-- 表格列 -->
              <template #default>
                <el-table-column type="selection" width="40" align="left" />
                <el-table-column v-if="false" prop="id" />
                <el-table-column
                  :label="$t('studymaterial.Dateiname')"
                  align="left"
                  prop="name"
                >
                  <template #default="scope">
                    <div
                      style="
                        display: flex;
                        width: 100%;
                        justify-content: space-between;
                      "
                      :class="
                        scope.row.id * 10 + scope.row.type === hoverRow
                          ? 'highlight'
                          : 'common'
                      "
                      @click="clickRow(scope.row)"
                    >
                      <div style="display: flex">
                        <svg-icon
                          :icon-class="
                            scope.row.type === 1
                              ? 'folder'
                              : scope.row.name.split('.').at(-1)
                          "
                          style="
                            font-size: 28px;
                            margin-right: 5px;
                            vertical-align: middle;
                          "
                        />
                        <span
                          class="middlea file-name"
                          style="vertical-align: middle"
                          @click.stop="fileClick(scope.row)"
                          >{{ scope.row.name }}</span
                        >
                      </div>
                      <div
                        v-if="scope.row.id * 10 + scope.row.type === hoverRow"
                        style="
                          white-space: nowrap;
                          z-index: 10;
                          text-overflow: ellipsis;
                        "
                      >
                        <el-tooltip
                          v-if="scope.row.type !== 1"
                          :content="$t('studymaterial.Vorschau')"
                          placement="bottom"
                          effect="light"
                        >
                          <svg-icon
                            :icon-class="'fd_view'"
                            class="operation_class"
                            style="
                              font-size: 18px;
                              line-height: 18px;
                              vertical-align: middle;
                            "
                            @click.stop="fileClick(scope.row)"
                          />
                        </el-tooltip>

                        <el-tooltip
                          :content="$t('studymaterial.Download')"
                          placement="bottom"
                          effect="light"
                        >
                          <svg-icon
                            v-throttle="() => handleDownload(scope.row)"
                            :icon-class="'fd_download'"
                            style="
                              margin-left: 14px;
                              font-size: 18px;
                              line-height: 18px;
                              vertical-align: middle;
                            "
                            class="operation_class"
                          />
                        </el-tooltip>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  :label="$t('studymaterial.Änderungszeit')"
                  align="left"
                  prop="updateTime"
                  width="300"
                />

                <el-table-column
                  :label="$t('studymaterial.Größe')"
                  align="left"
                  prop="size"
                  width="200"
                />
              </template>
            </el-table>
          </template>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
      v-model="imgVisible"
      append-to-body
      :title="$t('studymaterial.Vorschau')"
      style="width: 60%"
      @close="false"
    >
      <iframe :src="previewURL" style="width: 100%; height: 600px"></iframe>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Studymaterial",
  inheritAttrs: false,
});
import { downloadFile, downloadFiles } from "@/api/file";
import { FileTableInfo } from "@/api/file/types";
import { getStudyFiles } from "@/api/folder";
import { FileTableForm } from "@/api/folder/types";
import { useAppStore } from "@/store/modules/app";
import { useStudyStoreHook } from "@/store/modules/study";
import { formatbytes } from "@/utils/byte";
import { downloadBlob, downloadFilesAsync } from "@/utils/file";
import { ArrowRight } from "@element-plus/icons-vue";
import { useWindowSize } from "@vueuse/core";
const { height } = useWindowSize();
const calculatedValue = ref(0);

const folderId = ref<number | null>(null);
const ids = ref<FileTableForm[]>([]);
// 当前悬停的行
const hoverRow = ref(null);
const appStore = useAppStore();
const previewURL = ref("");
const loading = ref(false);
const imgVisible = ref(false);
const studyStore = useStudyStoreHook();
const tableRef = ref(ElTable);
const fileList = ref<FileTableInfo[]>([]);

type BreadType = {
  id?: number | null;
  name?: string;
};

const breadcrumbs = ref<BreadType[]>([
  {
    id: null,
    name: "全部文件",
  },
]);

const courseId = ref(studyStore.courseId);

watch(
  () => height.value,
  (newValue: any, oldValue: any) => {
    // const windowHeight = window.innerHeight;
    calculatedValue.value = newValue - 280;
  },
  { immediate: true }
);

function goBack() {
  breadcrumbs.value.pop();
  const back = breadcrumbs.value[breadcrumbs.value.length - 1];
  folderId.value = back.id!;
  handleQuery();
}

// 监听 mouseenter 事件
function handleMouseEnter(row: any, column: any, cell: any, event: any) {
  hoverRow.value = row.id * 10 + row.type;
}

function clickRow(row: any) {
  if (row.id != null) tableRef.value!.toggleRowSelection(row, undefined);
}

// 监听 mouseleave 事件
function handleMouseLeave(row: any, column: any, cell: any, event: any) {
  hoverRow.value = null;
}

// 下载文件
function handleDownload(row?: any) {
  if (!row) {
    downloadFilesAsync(ids.value);
  } else {
    // 使用三元运算符，简化判断row类型的if-else语句
    (row.type === 2
      ? downloadFile(row.path, row.name)
      : downloadFiles(
          ref<FileTableForm[]>([{ id: row.id, type: row.type }]).value
        )
    ).then((response) => {
      downloadBlob(response);
    });
  }
}

function fileClick(row: any) {
  if (row.type == 1) {
    folderId.value = row.id;
    breadcrumbs.value.push({
      id: row.id,
      name: row.name,
    });
    handleQuery();
  } else {
    const fileName = row.name.split(".");
    const fileExt = fileName.at(-1) ?? "";

    if (fileExt == "pdf") {
      previewURL.value = "http://bucket.chenz.xyz/" + row.path;
    } else {
      previewURL.value = row.url;
    }
    imgVisible.value = true;
  }
}

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => {
    return { id: item.id, type: item.type };
  });
}

// 监听点击链接
function handleLink(item: any) {
  const array = ref<BreadType[]>([]);
  for (let i = 0; i < breadcrumbs.value.length - 1; i++) {
    array.value.push(breadcrumbs.value[i]);

    if (breadcrumbs.value[i].id === item.id) {
      break;
    }
  }
  breadcrumbs.value = array.value;
  const back = breadcrumbs.value[breadcrumbs.value.length - 1];
  folderId.value = back.id!;
  handleQuery();
}

function handleQuery() {
  loading.value = true;

  getStudyFiles(folderId.value, courseId.value)
    .then(({ data }) => {
      fileList.value = [];

      data.folderList.forEach((folderItem) => {
        const folder: FileTableInfo = {
          name: folderItem.folderName,
          id: folderItem.folderId,
          updateTime: folderItem.updateTime,
          size: "-",
          type: 1,
        };
        fileList.value.push(folder);
      });

      data.fileList.forEach((fileItem) => {
        const file: FileTableInfo = {
          name: fileItem.fileName,
          id: fileItem.fileId,
          updateTime: fileItem.updateTime,
          size: formatbytes(fileItem.size),
          path: fileItem.path,
          url: fileItem.fileUrl,
          type: 2,
          downloadUrl: fileItem.downloadUrl,
        };
        fileList.value.push(file);
      });
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleQueryNoId() {
  loading.value = true;

  getStudyFiles(folderId.value, courseId.value)
    .then(({ data }) => {
      fileList.value = [];

      data.folderList.forEach((folderItem) => {
        const folder: FileTableInfo = {
          name: folderItem.folderName,
          id: folderItem.folderId,
          updateTime: folderItem.updateTime,
          size: "-",
          type: 1,
        };
        fileList.value.push(folder);
      });

      data.fileList.forEach((fileItem) => {
        const file: FileTableInfo = {
          name: fileItem.fileName,
          id: fileItem.fileId,
          updateTime: fileItem.updateTime,
          size: formatbytes(fileItem.size),
          path: fileItem.path,
          url: fileItem.fileUrl,
          type: 2,
          downloadUrl: fileItem.downloadUrl,
        };
        fileList.value.push(file);
      });
    })
    .finally(() => {
      loading.value = false;
    });
}

onMounted(() => {
  handleQuery();
});
</script>

<style lang="scss" scoped>
.dragm {
  opacity: 0.5;
  background-color: #f1f1f1;
  border: dashed 5px skyblue;
}

.textdrag {
  position: absolute;
  top: 30%;
  left: 30%;
  font-size: 38px;
}

.middlea {
  vertical-align: middle;
  display: table-cell;
  line-height: 28px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
  // color: var(--el-color-black);
}

.highlight {
  color: var(--el-menu-active-color);
  cursor: pointer;
}

.drop-zone {
  width: 300px;
  height: 200px;
  border: 2px dashed #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
}

.icon_class {
  color: var(--el-menu-active-color);
}

.file-name:hover {
  color: var(--el-menu-active-color);
}

.title {
  // color: var(color-scheme);
  // color: black;
  color: var(--text-black-color);
  font-weight: bold;
}

.common {
  color: var(--text-black-color);
}
</style>
